import 'dart:async';

import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/bean/attend_record_calendar_response_bean.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/even/attend_record_calendar_refresh_even.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

import '../attend_record_calendar_view_model.dart';
import 'modify_personal_clock_record_widget.dart';

class CalendarAttendanceStatusStatisticsWidget extends StatefulWidget {
  PunchRecordBean dayPunchRecordBeanValue;
  String fuid;
  final ValueNotifier<int> dateTimeValueNotifier;

  CalendarAttendanceStatusStatisticsWidget(
      {Key key, this.dayPunchRecordBeanValue, this.fuid, this.dateTimeValueNotifier})
      : super(key: key);

  @override
  _CalendarAttendanceStatusStatisticsWidgetState createState() =>
      _CalendarAttendanceStatusStatisticsWidgetState();
}

class _CalendarAttendanceStatusStatisticsWidgetState
    extends BaseState<CalendarAttendanceStatusStatisticsWidget> {
  StreamSubscription eventStreamSubscription;
  int page;
  DateTime selectedDayTime;
  @override
  void initState() {
    super.initState();
    page = 50;
    eventStreamSubscription =
        VgEventBus.global.on<CardMultiRefreshEvent>().listen((event) {
      widget?.dayPunchRecordBeanValue = event?.item;
      // _viewModel?.getRecordByMonthHttp(monthTimestramp, isReadCache, isPageChangeNotifier, callback);
      setState(() {});
    });
    selectedDayTime = DateTime?.parse(
        widget.dayPunchRecordBeanValue?.date ?? DateTime.now().toString());
  }

  @override
  void dispose() {
    eventStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // DateTime selectedDayTime = DateTime?.parse(
    //     widget.dayPunchRecordBeanValue?.date ?? DateTime.now().toString());
    // int appearNum = widget.dayPunchRecordBeanValue?.pcnt ?? 0;
    // bool _dayPunchRecordModifyDisplay = false;
    //上班状态 00出勤01缺勤 02纠正 03加班 04非加班 05请假 06外出 07确定加班 99异常',
    // String smallCardValue;
    // Color smallStatusCardFontColor;
    // Color smallStatusCardColor;
    // if (widget.dayPunchRecordBeanValue != null) {
    //   if (widget.dayPunchRecordBeanValue?.isNormal() ?? true) {
    //     smallCardValue = "正常";
    //     smallStatusCardColor = Color(0xFFD0E0F7);
    //     smallStatusCardFontColor = Color(0xFF191E31);
    //   }
    //   if (widget.dayPunchRecordBeanValue?.isException() ?? false) {
    //     smallCardValue = "异常";
    //     smallStatusCardColor = Color(0xFFFFB714);
    //     smallStatusCardFontColor = Color(0xFFFFFFFF);
    //   }
    //   if (widget.dayPunchRecordBeanValue?.isAbsence() ?? false) {
    //     smallCardValue = "缺勤";
    //     smallStatusCardColor = Color(0xFFF95355);
    //     smallStatusCardFontColor = Color(0xFFFFFFFF);
    //   }
    //   if (widget.dayPunchRecordBeanValue?.isOverTime() ?? false) {
    //     smallCardValue = "加班";
    //     smallStatusCardColor = Color(0xFF00C6C4);
    //     smallStatusCardFontColor = Color(0xFFFFFFFF);
    //   }
    //   // if(widget.dayPunchRecordBeanValue?.isRestNum() ?? false){
    //   //   smallCardValue = "正常";
    //   //   smallStatusCardColor = Color(0xFFD0E0F7);
    //   //   smallStatusCardFontColor = Color(0xFF191E31);
    //   // }
    // }
    //如果是今天
    //
    // if (widget?.dayPunchRecordBeanValue?.date ==
    //     "${DateTime.now()}".substring(0, 10)) {
    //   _showBorderColor = false;
    // }else{
    //   _showBorderColor = true;
    // }
    // if (widget?.dayPunchRecordBeanValue?.punchstatus == "03") {
    //   _dayPunchRecordModifyDisplay = true;
    // }
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // if (_dayPunchRecordModifyDisplay) {
        //   return;
        // }
        //单人整日数据界面
        ModifyPersonalClockRecordWidget.navigatorPush(
            context,
            // smallCardValue,
            // smallStatusCardColor,
            // widget.dayPunchRecordBeanValue?.cpid ?? "",
            getCurrentMonthTimeStramp(),
            widget?.fuid,
            DateTime?.parse(widget.dayPunchRecordBeanValue?.date ??
                DateTime.now().toString()),
                () {
          VgEventBus.global.send(AttendRecordCalendarRefreshEven());
          setState(() {});
        });
        // print("${ _getCurrentMonthTimeStramp(DateTime?.parse(
        //         widget.dayPunchRecordBeanValue?.date))
        // }");
        //路由器方法
        // RouterUtils.routeForFutureResult(
        //     context, ModifyPersonalClockRecordWidget(correctionBarColor: smallStatusCardColor,correctionBarText: smallCardValue,onTapCorrectionBar: (){
        //
        // }));
      },
      child: Column(
        children: <Widget>[
          Container(
            height: 67,
            decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color:ThemeRepository.getInstance().getPrimaryColor_1890FF(), width: 1),
            ),
            margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: _smallCardStatusBar(context),
          ),
        ],
      ),
    );
  }

  //蓝色标签
  Widget _blueLable(){
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(1.5),
        color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      ),
      width: 3,
      height: 14,
    );
  }

  //纠正图标
  Widget _correctionCard() {
    return Positioned(
      right: 0,
      top: 0,
      child: Image.asset(
        "images/correction_ico.png",
        width: 24,
      ),
    );
  }

  int getCurrentMonthTimeStramp() {
    DateTime _dateTime = DateTime?.parse(
        widget.dayPunchRecordBeanValue?.date ?? DateTime.now().toString());
    if (_dateTime == null) {
      return null;
    }
    return (DateTime(_dateTime.year, _dateTime.month, _dateTime.day)
                .millisecondsSinceEpoch /
            1000)
        .floor();
  }

  Widget _smallCardStatusBar(BuildContext context) {
    bool _dayPunchRecordModifyDisplay = false;
    int appearNum = widget.dayPunchRecordBeanValue?.pcnt ?? 0;
    String smallCardValue = "";
    Color smallStatusCardFontColor;
    Color smallStatusCardColor;
    if (widget.dayPunchRecordBeanValue != null) {
      if (widget.dayPunchRecordBeanValue?.isNormal()?? true) {
        smallCardValue = "正常";
        smallStatusCardColor = Color(0xFFD0E0F7);
        smallStatusCardFontColor = Color(0xFF191E31);
      }
      if (widget.dayPunchRecordBeanValue?.isLeave()?? true) {
        smallCardValue = "外出";
        smallStatusCardColor = Color(0xFFD0E0F7);
        smallStatusCardFontColor = Color(0xFF191E31);
      }
      if (widget.dayPunchRecordBeanValue?.isException() ?? false) {
        smallCardValue = "异常";
        smallStatusCardColor = Color(0xFFFFB714);
        smallStatusCardFontColor = Color(0xFFFFFFFF);
      }
      if (widget.dayPunchRecordBeanValue?.isAbsence() ?? false) {
        smallCardValue = "缺勤";
        smallStatusCardColor = Color(0xFFF95355);
        smallStatusCardFontColor = Color(0xFFFFFFFF);
      }
      if (widget.dayPunchRecordBeanValue?.isNotify() ?? false) {
        smallCardValue = "请假";
        smallStatusCardColor = Color(0xFFF95355);
        smallStatusCardFontColor = Color(0xFFFFFFFF);
      }
      if ((widget.dayPunchRecordBeanValue?.isOverTime() ?? false) || (widget.dayPunchRecordBeanValue?.isConfirmOverTime() ?? false)) {
        if(!(widget.dayPunchRecordBeanValue?.isConfirmOverTime() ?? false)){
          smallCardValue = "加班?";
          smallStatusCardColor = Colors.transparent;
          smallStatusCardFontColor = Color(0xFF00C6C4);
        }else{
          smallCardValue = "加班";
          smallStatusCardColor = Color(0xFF00C6C4);
          smallStatusCardFontColor = Color(0xFFFFFFFF);
        }
      }
      // if(widget.dayPunchRecordBeanValue?.isRestNum() ?? false){
      //   smallCardValue = "正常";
      //   smallStatusCardColor = Color(0xFFD0E0F7);
      //   smallStatusCardFontColor = Color(0xFF191E31);
      // }
      //如果不是休息日且有其他状态则显示
      if ((widget?.dayPunchRecordBeanValue?.isRest()??false)&&widget?.dayPunchRecordBeanValue?.punchstatus=="-1" || (widget.dayPunchRecordBeanValue?.isRestNum()??false)) {
        _dayPunchRecordModifyDisplay = false;
      }else{
        _dayPunchRecordModifyDisplay = true;
      }
      // if (widget?.dayPunchRecordBeanValue?.mintime == 0) {
      //   _dayPunchRecordModifyDisplay = false;
      // }
      //如果是今天
      // if (widget?.dayPunchRecordBeanValue?.date ==
      //     "${DateTime.now()}".substring(0, 10)) {
      //   _dayPunchRecordModifyDisplay = false;
      // }
    }
    if(widget?.dayPunchRecordBeanValue?.maxtime==0){
      widget?.dayPunchRecordBeanValue?.maxtime = widget?.dayPunchRecordBeanValue?.mintime;
    }
    return Stack(
      children: [
        Row(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Expanded(
              child: Column(
                children: <Widget>[
                  Spacer(
                    flex: 8,
                  ),
                  // SizedBox(height: 10,),
                  Row(
                    children: [
                      _blueLable(),
                      SizedBox(width: 10.5,),
                      dailyCorrectionTitleBarWidget(),
                      Opacity(
                        opacity:appearNum == 0?0:1 ,
                        child: Container(
                          // padding: const EdgeInsets.only(top: 10),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            " · 刷脸${appearNum ?? 0}次",
                            style: TextStyle(
                                fontSize: 15, color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ),
                    ],
                  ),
                  // if (VgToolUtils.getHourAndMinuteStr(
                  //         widget?.dayPunchRecordBeanValue?.maxtime) !=
                  //     null)
                    Spacer(
                      flex: 3,
                    ),
                    // SizedBox(height: 6,),
                  // if (VgToolUtils.getHourAndMinuteStr(
                  //         widget?.dayPunchRecordBeanValue?.maxtime) !=
                  //     null)
                    Container(
                      height: 15,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.only(left: 15),
                      child:widget?.dayPunchRecordBeanValue?.backup != null&&widget?.dayPunchRecordBeanValue?.backup !="" ?_remarkInformation() :_punchInformation(),
                    ),
                  Spacer(
                    flex: 8,
                  ),
                ],
              ),
            ),

            // SizedBox(width: 140,),
            // Spacer(),
            //如果不是休息日且有其他状态则显示
            if (_dayPunchRecordModifyDisplay)
              Container(
                padding: const EdgeInsets.only(right: 16),
                alignment: Alignment.centerRight,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    if(smallCardValue!="")
                    Container(
                      height: 16,
                      width: 30,
                      decoration: BoxDecoration(
                        color: smallStatusCardColor ?? Color(0xFFD0E0F7),
                        borderRadius: BorderRadius.circular(2),
                      ),
                      child: Center(
                        child: Text(
                          "${smallCardValue ?? "正常"}",
                          style: TextStyle(
                              fontSize: 10,
                              color: smallStatusCardFontColor,
                              height: 1.4),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                    Image.asset(
                      "images/index_arrow_ico.png",
                      width: 6,
                      color: Color(0xFFFFFFFF),
                    ),
                  ],
                ),
              ),
          ],
        ),

        //如果纠正过之后添加此标签
        if (widget?.dayPunchRecordBeanValue?.punchstatus == "02")
          _correctionCard(),
      ],
    );
  }

  Widget dailyCorrectionTitleBarWidget(){
    selectedDayTime = DateTime?.parse(
        widget.dayPunchRecordBeanValue?.date ?? DateTime.now().toString());
    return ValueListenableBuilder(
      valueListenable: widget?.dateTimeValueNotifier,
        builder: (BuildContext context, int pageValue, Widget child) {
         return Container(
            // padding: const EdgeInsets.only(left: 12),
            child: Row(
              children: <Widget>[
                // Container(
                //   decoration: BoxDecoration(
                //     borderRadius: BorderRadius.circular(1.5),
                //     color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                //   ),
                //   width: 3,
                //   height: 14,
                // ),
                // SizedBox(width: 7),
                Text(
                  "${"${selectedDayTime?.month}月${selectedDayTime?.day}日"}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 15,
                      fontWeight: FontWeight.w600),
                )
              ],
            ),
          );
        }
    );
  }

  Widget _remarkInformation(){
    return Text(
      "${widget?.dayPunchRecordBeanValue?.backup ?? ""}",
      style: TextStyle(
          fontSize: 13,
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          height: 1.3),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  Widget _punchInformation(){
    return Text(
      "${VgToolUtils.getHourAndMinuteStr(widget?.dayPunchRecordBeanValue?.maxtime) ?? "暂无刷脸记录"}  ${widget?.dayPunchRecordBeanValue?.position ?? ""}",
      style: TextStyle(
          fontSize: 13,
          color: Color(0xFF808388),
          height: 1.3),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }
}

//选择日期
class DailyCorrectionTitleBarWidget extends StatefulWidget {
  PunchRecordBean dayPunchRecordBeanValue;

  DailyCorrectionTitleBarWidget({Key key, this.dayPunchRecordBeanValue})
      : super(key: key);

  @override
  _DailyCorrectionTitleBarWidgetState createState() =>
      _DailyCorrectionTitleBarWidgetState();
}

class _DailyCorrectionTitleBarWidgetState
    extends State<DailyCorrectionTitleBarWidget> {
  @override
  Widget build(BuildContext context) {
    DateTime selectedDayTime = DateTime?.parse(
        widget.dayPunchRecordBeanValue?.date ?? DateTime.now().toString());
    return Container(
      // padding: const EdgeInsets.only(left: 12),
      child: Row(
        children: <Widget>[
          // Container(
          //   decoration: BoxDecoration(
          //     borderRadius: BorderRadius.circular(1.5),
          //     color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          //   ),
          //   width: 3,
          //   height: 14,
          // ),
          // SizedBox(width: 7),
          Text(
            "${"${selectedDayTime?.month}月${selectedDayTime?.day}日"}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 15,
                fontWeight: FontWeight.w600),
          )
        ],
      ),
    );
  }
}
